// 免费试算表单功能实现
(function() {
  'use strict';
  
  // 全局变量 - 只保留必要的
  let modalElement = null;
  let formElement = null;
  let submitButton = null;
  
  // 常量定义 - 统一使用的ID和选择器
  const MODAL_CLASS = 'trial-modal';
  const FORM_ID = 'trial-calculation-form';
  const SUBMIT_BUTTON_ID = 'trial-submit-btn';
  const OPEN_BUTTON_SELECTORS = '.btn-try, .btn-calculate';
  
  /**
   * 初始化免费试算表单
   * 简化初始化逻辑，确保DOM元素正确获取和事件绑定
   */
  function initTrialForm() {
    console.log('开始初始化免费试算表单');
    
    // 检查并创建模态框
    checkAndCreateModal();
    
    // 重新获取元素引用
    getFormElements();
    
    // 绑定事件
    bindEvents();
    
    // 创建全局调试函数
    window.debugSubmitTrialForm = function() {
      console.log('手动触发表单提交调试函数');
      getFormElements();
      if (submitButton) {
        submitButton.click();
      } else {
        console.log('手动触发失败：提交按钮不存在');
      }
    };
    
    console.log('免费试算表单初始化完成');
  }
  
  /**
   * 检查并创建模态框
   */
  function checkAndCreateModal() {
    // 检查是否已存在模态框
    modalElement = document.querySelector('.' + MODAL_CLASS);
    
    // 如果不存在，创建模态框
    if (!modalElement) {
      createTrialModal();
      modalElement = document.querySelector('.' + MODAL_CLASS);
    }
  }
  
  /**
   * 创建免费试算模态框
   * 确保提交按钮的ID和类型一致
   */
  function createTrialModal() {
    console.log('创建免费试算模态框');
    
    // 创建模态框容器
    const modalContainer = document.createElement('div');
    modalContainer.className = MODAL_CLASS;
    modalContainer.style.cssText = `
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 1000;
      justify-content: center;
      align-items: center;
    `;
    
    // 设置模态框HTML内容
    modalContainer.innerHTML = `
      <div class="trial-modal-overlay"></div>
      <div class="trial-modal-content">
        <div class="trial-modal-header">
          <h2 class="trial-modal-title"><i class="fas fa-calculator" style="margin-right: 10px;"></i>免费试算申请</h2>
          <button class="trial-modal-close" aria-label="关闭">&times;</button>
        </div>
        
        <div class="trial-modal-body">
          <form id="${FORM_ID}" class="trial-form">
            <!-- 表单行1 -->
            <div class="trial-form-row">
              <div class="trial-form-group">
                <label for="trial-name" class="trial-form-label required">姓名</label>
                <input type="text" id="trial-name" name="name" class="trial-form-control" placeholder="请输入您的姓名" required>
              </div>
              <div class="trial-form-group">
                <label for="trial-phone" class="trial-form-label required">手机号码</label>
                <input type="tel" id="trial-phone" name="phone" class="trial-form-control" placeholder="请输入您的手机号码" required>
              </div>
            </div>
            
            <!-- 表单行2 -->
            <div class="trial-form-row">
              <div class="trial-form-group">
                <label for="trial-company" class="trial-form-label required">单位名称</label>
                <input type="text" id="trial-company" name="company" class="trial-form-control" placeholder="请输入您的单位名称" required>
              </div>
              <div class="trial-form-group">
                <label for="trial-email" class="trial-form-label">邮箱</label>
                <input type="email" id="trial-email" name="email" class="trial-form-control" placeholder="请输入您的邮箱地址">
              </div>
            </div>
            
            <!-- 表单行3 -->
            <div class="trial-form-row">
              <div class="trial-form-group">
                <label for="trial-industry" class="trial-form-label required">所属行业</label>
                <select id="trial-industry" name="industry" class="trial-form-control" required>
                  <option value="">请选择行业</option>
                  <option value="financial">金融</option>
                  <option value="manufacturing">制造业</option>
                  <option value="scientific">科研教育</option>
                  <option value="medical">医疗健康</option>
                  <option value="energy">能源</option>
                  <option value="internet">互联网</option>
                  <option value="government">政府</option>
                  <option value="other">其他</option>
                </select>
              </div>
              <div class="trial-form-group">
                <label for="trial-service" class="trial-form-label required">意向产品</label>
                <select id="trial-service" name="service" class="trial-form-control" required>
                  <option value="">请选择产品</option>
                  <option value="general-cloud">通用云</option>
                  <option value="industry-cloud">行业云</option>
                  <option value="ai-cloud">AI云</option>
                  <option value="simulation-cloud">仿真设计云</option>
                  <option value="hpc">高性能计算</option>
                  <option value="other">其他服务</option>
                </select>
              </div>
            </div>
          </form>
        </div>
        
        <div class="trial-modal-footer">
          <button type="button" id="${SUBMIT_BUTTON_ID}" class="trial-form-btn trial-form-btn-primary">
            <i class="fas fa-paper-plane"></i> 提交申请
          </button>
        </div>
      </div>
    `;
    
    // 添加到页面
    document.body.appendChild(modalContainer);
    
    // 确保样式正确应用
    ensureButtonStyles();
  }
  
  /**
   * 确保按钮样式正确应用
   */
  function ensureButtonStyles() {
    if (!document.getElementById('trial-button-styles')) {
      const styleElement = document.createElement('style');
      styleElement.id = 'trial-button-styles';
      styleElement.textContent = `
        /* 确保提交按钮样式正确应用 */
        .trial-form-btn {
          padding: 12px 24px;
          border: none;
          border-radius: 6px;
          font-size: 1rem;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s ease;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          outline: none;
        }
        
        .trial-form-btn-primary {
          background-color: var(--primary-color, #1E88E5);
          color: white;
        }
        
        .trial-form-btn-primary:hover {
          background-color: #1565C0;
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(30, 136, 229, 0.3);
        }
        
        .trial-form-btn-primary:disabled {
          background-color: #ccc;
          cursor: not-allowed;
          transform: none;
          box-shadow: none;
        }
      `;
      document.head.appendChild(styleElement);
    }
  }
  
  /**
   * 获取表单元素引用
   * 统一使用document.getElementById获取关键元素，提高性能和可靠性
   */
  function getFormElements() {
    formElement = document.getElementById(FORM_ID);
    submitButton = document.getElementById(SUBMIT_BUTTON_ID);
    
    console.log('表单元素状态:', {
      formElement: formElement ? '存在' : '不存在',
      submitButton: submitButton ? '存在' : '不存在'
    });
  }
  
  /**
   * 绑定事件处理程序
   * 简化事件绑定逻辑，避免重复绑定和事件丢失
   */
  function bindEvents() {
    console.log('开始绑定事件处理程序');
    
    // 如果元素不存在，先获取
    if (!formElement || !submitButton) {
      getFormElements();
    }
    
    // 模态框关闭相关事件
    if (modalElement) {
      const closeButtons = modalElement.querySelectorAll('.trial-modal-close');
      const overlay = modalElement.querySelector('.trial-modal-overlay');
      const content = modalElement.querySelector('.trial-modal-content');
      
      // 关闭按钮事件
      if (closeButtons.length > 0) {
        closeButtons.forEach(button => {
          button.addEventListener('click', closeTrialModal);
        });
      }
      
      // 点击遮罩层关闭
      if (overlay) {
        overlay.addEventListener('click', closeTrialModal);
      }
      
      // 阻止内容区域的点击事件冒泡
      if (content) {
        content.addEventListener('click', function(e) {
          e.stopPropagation();
        });
      }
    }
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
      if (e.key === 'Escape' && modalElement && modalElement.style.display === 'flex') {
        closeTrialModal();
      }
    });
    
    // 为所有免费试算按钮添加点击事件 - 使用事件委托
    document.addEventListener('click', function(e) {
      if (e.target.closest(OPEN_BUTTON_SELECTORS)) {
        getFormElements(); // 确保元素引用是最新的
        openTrialModal();
      }
    });
    
    // 最重要的：提交按钮点击事件
    if (submitButton) {
      // 移除旧事件监听器的最佳方式是直接绑定新的
      // 避免使用cloneNode导致的问题
      submitButton.onclick = function() {
        console.log('提交按钮点击事件触发');
        submitTrialForm();
      };
      
      console.log('提交按钮点击事件已成功绑定');
    } else {
      console.log('警告：未找到提交按钮，添加全局安全机制');
      // 全局安全机制
      window.forceSubmitTrialForm = function() {
        getFormElements();
        if (submitButton) {
          submitButton.click();
        }
      };
    }
    
    // 表单提交事件 - 保留用于直接提交的情况
    if (formElement) {
      formElement.addEventListener('submit', function(e) {
        e.preventDefault();
        console.log('表单提交事件触发');
        submitTrialForm();
      });
    }
    
    console.log('事件绑定完成');
  }
  
  /**
   * 打开模态框
   */
  function openTrialModal() {
    if (!modalElement) {
      console.error('错误：模态框元素不存在');
      return;
    }
    
    modalElement.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // 滚动到模态框顶部
    const modalContent = modalElement.querySelector('.trial-modal-content');
    if (modalContent) {
      modalContent.scrollTop = 0;
    }
    
    console.log('免费试算模态框已打开');
  }
  
  /**
   * 关闭模态框
   */
  function closeTrialModal() {
    if (!modalElement) return;
    
    modalElement.style.display = 'none';
    document.body.style.overflow = '';
    
    console.log('免费试算模态框已关闭');
  }
  
  /**
   * 表单验证
   * 一次性验证所有字段，将错误字段变红，不使用弹窗提示
   */
  function validateTrialForm() {
    console.log('开始表单验证');
    
    if (!formElement) {
      console.error('错误：表单元素不存在');
      return false;
    }
    
    // 清除之前的错误状态
    clearFormErrors();
    
    let isValid = true;
    
    // 验证必填项
    const requiredFields = [
      { id: 'trial-name', label: '姓名' },
      { id: 'trial-phone', label: '手机号码' },
      { id: 'trial-company', label: '单位名称' },
      { id: 'trial-industry', label: '所属行业' },
      { id: 'trial-service', label: '意向产品' }
    ];
    
    // 存储第一个错误字段，用于后续聚焦
    let firstErrorField = null;
    
    // 一次性验证所有字段
    for (let i = 0; i < requiredFields.length; i++) {
      const fieldInfo = requiredFields[i];
      const field = document.getElementById(fieldInfo.id);
      
      if (field) {
        // 验证必填
        if (!field.value.trim()) {
          markFieldAsError(field);
          isValid = false;
          if (!firstErrorField) firstErrorField = field;
        }
        
        // 手机号格式验证
        if (fieldInfo.id === 'trial-phone' && field.value.trim()) {
          const phonePattern = /^1[3-9]\d{9}$/;
          if (!phonePattern.test(field.value)) {
            markFieldAsError(field);
            isValid = false;
            if (!firstErrorField) firstErrorField = field;
          }
        }
      }
    }
    
    // 邮箱格式验证（非必填）
    const emailField = document.getElementById('trial-email');
    if (emailField && emailField.value.trim()) {
      const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailPattern.test(emailField.value.trim())) {
        markFieldAsError(emailField);
        isValid = false;
        if (!firstErrorField) firstErrorField = emailField;
      }
    }
    
    // 聚焦到第一个错误字段
    if (!isValid && firstErrorField) {
      firstErrorField.focus();
    }
    
    console.log('表单验证结果:', isValid);
    return isValid;
  }
  
  /**
   * 将表单字段标记为错误状态
   */
  function markFieldAsError(field) {
    // 添加错误样式类
    field.classList.add('trial-form-control-error');
    
    // 确保有对应的CSS样式
    ensureErrorStyles();
    
    console.log('字段标记为错误:', field.id);
  }
  
  /**
   * 清除表单所有错误状态
   */
  function clearFormErrors() {
    const errorFields = document.querySelectorAll('.trial-form-control-error');
    errorFields.forEach(field => {
      field.classList.remove('trial-form-control-error');
    });
  }
  
  /**
   * 确保错误样式已加载
   */
  function ensureErrorStyles() {
    if (!document.getElementById('trial-error-styles')) {
      const styleElement = document.createElement('style');
      styleElement.id = 'trial-error-styles';
      styleElement.textContent = `
        .trial-form-control-error {
          border-color: #e53e3e !important;
          background-color: #fff5f5 !important;
        }
        .trial-form-control-error:focus {
          border-color: #e53e3e !important;
          box-shadow: 0 0 0 3px rgba(229, 62, 62, 0.1) !important;
        }
      `;
      document.head.appendChild(styleElement);
    }
  }
  
  /**
   * 提交表单
   * 确保表单提交流程简单、可靠
   */
  function submitTrialForm() {
    // 确保元素引用是最新的
    getFormElements();
    
    if (!formElement) {
      console.error('错误：表单元素不存在');
      alert('表单初始化失败，请刷新页面后重试');
      return;
    }
    
    if (!submitButton) {
      console.error('错误：提交按钮不存在');
      alert('提交按钮初始化失败，请刷新页面后重试');
      return;
    }
    
    console.log('开始表单提交流程');
    
    // 验证表单
    if (!validateTrialForm()) {
      console.log('表单验证失败，提交中断');
      return;
    }
    
    // 显示加载状态
    submitButton.disabled = true;
    const originalText = submitButton.innerHTML;
    submitButton.innerHTML = '<span style="display: inline-block; width: 16px; height: 16px; border: 2px solid rgba(255,255,255,.3); border-radius: 50%; border-top-color: white; animation: spin 1s ease-in-out infinite; margin-right: 8px;"></span> 提交中...';
    
    // 添加旋转动画样式
    if (!document.getElementById('trial-loading-style')) {
      const styleElement = document.createElement('style');
      styleElement.id = 'trial-loading-style';
      styleElement.textContent = `
        @keyframes spin { to { transform: rotate(360deg); } }
      `;
      document.head.appendChild(styleElement);
    }
    
    // 收集表单数据
    const formData = new FormData(formElement);
    const formValues = Object.fromEntries(formData.entries());
    console.log('提交的表单数据:', formValues);
    
    // 模拟表单提交
    setTimeout(() => {
      // 显示成功提示
      alert('您的免费试算申请已提交成功，我们将尽快与您联系！');
      
      // 恢复按钮状态
      submitButton.disabled = false;
      submitButton.innerHTML = originalText;
      
      // 重置表单
      formElement.reset();
      
      // 关闭模态框
      closeTrialModal();
      
      console.log('表单提交流程完成');
    }, 1500);
  }
  
  // 确保DOM加载完成后初始化
  function init() {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initTrialForm);
    } else {
      initTrialForm();
    }
  }
  
  // 导出初始化函数
  window.initTrialForm = init;
  
  // 自动初始化
  init();
})();